package com.moxiao.yfjh.module.blind.common;


import cn.hutool.json.JSONObject;
import com.moxiao.yfjh.framework.common.util.date.DateUtils;
import com.moxiao.yfjh.module.blind.controller.admin.member.vo.BlindMemberUserCreateReqVO;
import com.moxiao.yfjh.module.blind.dal.dataobject.member.BlindMemberUserDO;
import com.moxiao.yfjh.module.blind.service.member.BlindMemberUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.Objects;
import java.util.Optional;

import static com.moxiao.yfjh.module.system.mq.kafka.KafkaProducer.KAFKA_BLIND_MEMBER_USER_KEY;


/**
 * 用户注册 Consumer
 */
//@Tag(name = "注册H5 - 相亲用户H5注册")
@Component
@Slf4j
public class RegisterKafkaConsumer {

    @Resource
    private BlindMemberUserService blindMemberUserService;

    private static final String PREFIX_USER = "HY";

    @KafkaListener(topics = {KAFKA_BLIND_MEMBER_USER_KEY})
    public void listen(ConsumerRecord<?, ?> record) {
        Optional.ofNullable(record.value())
                .ifPresent(
                        message -> {
                            log.info("【消费者接收会员用户注册message : {}】", message);
                            try {
                                JSONObject jsonObject = new JSONObject(message);
//                                // 注册时间
//                                String createTime = jsonObject.get("createTime").toString();
//                                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                                Date date = dateFormat.parse(createTime);
                                BlindMemberUserCreateReqVO createReqVO = new BlindMemberUserCreateReqVO();
                                createReqVO.setMobile(jsonObject.get("mobile").toString());
                                createReqVO.setPesence((byte) 1);
                                createReqVO.setRegisterIp(jsonObject.get("mobile").toString());
                                //TODO 分销员
                                createReqVO.setDistributors(jsonObject.get("distributors").toString());
//                                createReqVO.setNo(jsonObject.get("no").toString());
                                registerUser(createReqVO);
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        });
    }

    /**
     * 消费者消息处理：处理用户注册,开始为用户注册
     */
//    @Operation(summary = "相亲-用户H5注册")
    public void registerUser(BlindMemberUserCreateReqVO createReqVO) {

        BlindMemberUserDO blindMemberUserDO = blindMemberUserService.selectByMobile(createReqVO.getMobile());
        if (Objects.isNull(blindMemberUserDO)) {
            createReqVO.setUserNo(createReqVO.getNo());
            addUserNo(createReqVO);
            blindMemberUserService.createMemberUser(createReqVO);
            String str = "手机号为：" + createReqVO.getMobile() + "的用户，注册成功！";
            log.info("【会员用户注册成功 : {}】", str);
        } else {
            String str = "手机号为【" + createReqVO.getMobile() + "】号已注册，不能重复注册！";
            log.error("【注册失败 : {}】", str);
//            throw exception(MEMBER_USER_PHONE_EXISTS);
        }
    }

    /**
     * 增加 userNo(用户编号)字段
     *
     * @param createReqVO
     */

    public void addUserNo(BlindMemberUserCreateReqVO createReqVO) {
        BlindMemberUserDO blindMemberUserDO = blindMemberUserService.getMemberUserTodayLast(DateUtils.getTodayStart(), DateUtils.getTodayEnd());
        DecimalFormat formatCount = new DecimalFormat("0000");
        int dateTime = Integer.parseInt(DateUtils.dateTime());
        if (Objects.nonNull(blindMemberUserDO)) {
            String[] user_no = blindMemberUserDO.getUserNo().split("_");
            String lastPart = user_no[user_no.length - 1];
            if (user_no.length > 1) {
                Integer num = Integer.parseInt(lastPart) + 1;
                String no = formatCount.format(num);
                createReqVO.setUserNo(PREFIX_USER + "_" + dateTime + "_" + no);
            }
        } else {
            String user_no = PREFIX_USER + "_" + dateTime + "_" + "0001";
            Integer num = blindMemberUserService.getMemberUserNo(user_no);
            if (num == 0) {
                createReqVO.setUserNo(user_no);
            }
        }
    }

}
